#!/usr/bin/env perl

use strict;
use warnings;
use POSIX;
use Data::Dumper;

my $DATA_DIR = ".";
my $METADATA_FILE = "metadata.txt";
my $CONTENT_FILE = "content.html";
my $SITEMAP_FILE = "sitemap.xml";
my $BASE_URL = "http://www.myfishinghome.com";

# make a list of all directories
sub generate_dir_list {
  my @dirs = ();
  open (my $fh, "-|", "find", "$DATA_DIR", "-type", "d" );
  while (<$fh>) {
    my $dir = $_;
    chomp($dir);
    push @dirs, $dir if -e "$dir/$METADATA_FILE";
  }
  close($fh);
  return @dirs;
}

MAIN:
{
	my @dirs = generate_dir_list();
	my $sitemap = "";

	foreach my $dir (@dirs) {
		my $priority = $dir eq $DATA_DIR ? 1 : 0.5;
		my $lastmod = POSIX::strftime("%Y-%m-%d", 
				localtime((stat "$dir/$CONTENT_FILE")[9]));
		$dir =~ s/\.//gis;
		my $loc = "$BASE_URL$dir/";
		my $str = "<loc>$loc</loc>\n";
		$str .= "<lastmod>$lastmod</lastmod>\n"	;
		$str .= "<changefreq>weekly</changefreq>\n";
		$str .= "<priority>$priority</priority>\n";
		$sitemap .= "<url>\n$str</url>\n";
	}
	my $xml_header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	$xml_header .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

	my $xml_footer = "</urlset>\n";	

	my $xml = $xml_header . $sitemap . $xml_footer;
	open F, ">$SITEMAP_FILE";
	print F $xml;
	close F;	
}
